package cn.com.taurus.dispose;

import cn.com.taurus.biz.AdminsBiz;
import cn.com.taurus.biz.PowerManagerBiz;
import cn.com.taurus.entity.Admins;
import cn.com.taurus.entity.PowerManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class UserSecurityService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    PowerManagerBiz powerManagerBiz;
    @Autowired
    AdminsBiz adminsBiz;
    public static Admins admins = new Admins();

    /**
     * 认证授权
     * @param aAccount
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String aAccount) throws UsernameNotFoundException {
        admins = adminsBiz.selectAdmisByAAccount(aAccount);
        System.out.println(admins.toString());
        if(admins==null) {
            //如果用户查不到，就返回空
            return null;
        }
        List<PowerManager> list = powerManagerBiz.selectPmNameByAId(admins.getaId());

        List<String> stringList = new ArrayList<>();

        String[] powerManagers = new String[list.size()]; //查询权限

        for (int i = 0; i < list.size(); i++)  {
            PowerManager powerManager = list.get(i);
            powerManagers[i]=powerManager.getPmName();
            stringList.add(powerManager.getPmName());
        }

        System.out.println();
        UserDetails user = User.
                withUsername(admins.getaAccount()).
                password(passwordEncoder.encode(admins.getaPassword())).
                authorities(powerManagers).build();

        System.err.println("密码加密："+passwordEncoder.encode(admins.getaPassword()));
        return user;
    }

}
